// pages/audio_guide/audio_guide.js
Page({
  data: {
    chapterList: [],
    currentIndex: 0
  },
  onLoad() {
    this.setNavigation();
    this.fetchChapterList();
  },
  setNavigation() {
    try { wx.setNavigationBarTitle({ title: '语音导览' }); } catch(e) {}
  },
  fetchChapterList() {
    const apiUrl = 'https://nzy-api.congqian.cn/Api/admin/exhibit_one/get_exhibit_list';
    wx.request({
      url: apiUrl,
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.code === 200 && res.data.data) {
          const payload = res.data.data;
          const list = (payload && (payload.one || payload)) || [];
          const chapters = list.map(ch => {
            const children = (ch.children || ch.list || []);
            const coverFromSelf = this.getCoverFromItem(ch);
            const coverFromFirstChild = children.length ? this.getCoverFromItem(children[0]) : '';
            const summaryFromSelf = (ch && ch.brief !== undefined && ch.brief !== null) ? String(ch.brief) : this.extractSummary(ch.content || '');
            const summaryFromChild = children.length ? ((children[0] && children[0].brief !== undefined && children[0].brief !== null) ? String(children[0].brief) : this.extractSummary(children[0].content || '')) : '';
            const firstExhibitId = children && children.length ? children[0].id : null; // 新增：用于直接跳转展项

            return {
              id: ch.id,
              name: ch.name,
              cover: coverFromSelf || coverFromFirstChild || (ch.icon ? this.normalizeUrl(ch.icon) : 'https://nzy.gonng.com/storage/mini/home.png'),
              summary: summaryFromSelf || summaryFromChild,
              count: children.length,
              firstExhibitId // 新增字段
            };
          });
          this.setData({ chapterList: chapters });
        }
      },
      fail: () => { wx.showToast({ title: '加载失败', icon: 'none' }); }
    });
  },
  getBaseOrigin() { return 'https://nzy-api.congqian.cn'; },
  normalizeUrl(url) {
    if (!url) return '';
    try { url = String(url).replace(/[`'\"]/g, '').trim(); } catch(e) {}
    if (/^https?:\/\//i.test(url)) return url;
    const base = this.getBaseOrigin();
    return url.startsWith('/') ? base + url : base + '/' + url;
  },
  getCoverFromItem(node){
    if (!node) return '';
    const arr = node.item || node.resource || node.resources || [];
    if (Array.isArray(arr) && arr.length>0){
      // 优先取图片类型的第一个，其次任意第一个
      let first = null;
      for (let i=0;i<arr.length;i++){
        const r = arr[i] || {};
        if (Number(r.type) === 1) { first = r; break; }
      }
      if (!first) { first = arr[0] || {}; }
      const url = first.url || first.path || first.src || first.file || first.file_url || first.filePath || first.link;
      if (url) return this.normalizeUrl(url);
    }
    return '';
  },
  toPlainText(input){
    if (!input) return '';
    const text = String(input).replace(/<[^>]+>/g, '').replace(/\s+/g, ' ').trim();
    return text.length>120 ? text.slice(0,120) + '…' : text;
  },
  extractSummary(html) {
    if (!html) return '';
    try {
      return this.toPlainText(html);
    } catch(e) { return ''; }
  },
  onSwiperChange(e){
    const i = e && e.detail && typeof e.detail.current==='number' ? e.detail.current : 0;
    this.setData({ currentIndex: i });
  },
  goChapter(e) {
    const id = e.currentTarget.dataset.id;
    if (!id) return;
    // 改为直接进入该篇章的第一个展项详情
    const idStr = String(id);
    const chapter = (this.data.chapterList || []).find(c => String(c.id) === idStr);
    const firstId = chapter && (chapter.firstExhibitId != null ? chapter.firstExhibitId : null);
    if (firstId) {
      wx.navigateTo({ url: `/pages/exhibition/exhibit?exhibitId=${firstId}` });
    } else {
      wx.showToast({ title: '该篇章暂无展项', icon: 'none' });
    }
  }
});